//页面级视图-存储卡读取权限
import React from 'react';
import {View, Alert} from 'react-native';
import {useDebounceEffect, useMount, useSafeState, useUnmount} from 'ahooks';
import {Text, Button} from '@rneui/base';
import {
  check,
  request,
  PERMISSIONS,
  openSettings,
  RESULTS,
} from 'react-native-permissions';

export default ({children}) => {
  const [storageReadStatusTxt, setStorageReadStatusTxt] = useSafeState();
  const isLoading = storageReadStatusTxt === undefined;
  const isAllow = storageReadStatusTxt === RESULTS.GRANTED;
  useMount(async () => {
    let v = '';
    try {
      v = await check(PERMISSIONS.IOS.PHOTO_LIBRARY);
    } catch (e) {
      v = 'denied';
    }
    setStorageReadStatusTxt(v);
  });

  if (isLoading) {
    return <></>;
  }
  if (!isAllow) {
    return (
      <>
        <View
          style={{
            flex: 1,
            alignItems: 'center',
            justifyContent: 'center',
          }}>
          <Text>使用网盘需要授权：“照片”{'->'}“所有照片”权限</Text>
          <Button
            title="授权"
            buttonStyle={{backgroundColor: 'rgba(214, 61, 57, 1)'}}
            containerStyle={{
              height: 40,
              width: 200,
              // marginHorizontal: 50,
              marginVertical: 20,
            }}
            titleStyle={{color: 'white'}}
            onPress={async () => {
              let v = '';
              try {
                v = await request(PERMISSIONS.IOS.PHOTO_LIBRARY);
              } catch (e) {
                Alert.alert('操作失败', e.message);
                return;
              }
              console.log('v', v);
              if (v !== RESULTS.GRANTED) {
                openSettings().catch(() =>
                  Alert.alert('操作失败', '打开系统设置'),
                );
              } else {
                setStorageReadStatusTxt(v);
              }
            }}
          />
        </View>
      </>
    );
  }
  return children;
};
